<template>
  <ScrollContainer class="pr-4" v-loading="loading" :loading-tip="t('common.loadingText')">
    <div class="flex justify-around w-1/2 m-auto">
      <a-button @click="handleResetFields">清除</a-button>
      <a-button v-if="type == 1" @click="handleType(2)" class="ml-2">外部</a-button>
      <a-button v-else @click="handleType(1)" class="ml-2">模块</a-button>
      <a-button type="primary" @click="customSubmitFunc" :loading="loading" class="ml-2"
        >保存</a-button
      >
    </div>
    <BasicForm @register="registerForm">
      <template #divider-basic2>
        <Divider orientation="left">
          <a-button
            type="primary"
            ghost
            @click="handleConfigView"
            v-if="dataRef?.conditionList?.length"
          >
            <SettingOutlined title="配置条件" />
          </a-button>
          <a-button type="default" @click="handleConfigView" v-else>
            <SettingOutlined title="配置条件" />
          </a-button>
        </Divider>
      </template>
      <template #fieldName>
        <FormItemRest>
          <div
            v-for="(item, index) in dataRef.writeBackFieldList"
            :key="'fieldName' + index"
            class="mb-2"
          >
            <div>
              <div class="flex items-center mb-2">
                <div class="w-150px">设置字段值</div>
                <Select
                  :options="fieldsDataOptions"
                  v-model:value="item.fieldName"
                  v-if="type == 1"
                />
                <Select :options="tableFieldsData" v-model:value="item.fieldName" v-else />
                <div class="w-80px text-center">
                  <PlusOutlined
                    class="ml-2 mr-2 cursor-pointer"
                    @click="handleAdd"
                    v-if="index + 1 == writeBackFieldListLen"
                  />
                  <MinusOutlined
                    class="cursor-pointer"
                    style="color: red"
                    @click="handleDelete(index)"
                  />
                </div>
              </div>
              <div class="flex items-center">
                <InputTextArea
                  v-model:value="item.writeBackMath"
                  :readonly="item.readonly"
                  @click="handleClickArea(item, index)"
                />
                <!-- <a-button
                  type="primary"
                  class="ml-2"
                  size="small"
                  @click="handleSelectField1(item, index)"
                  >选择</a-button
                > -->
              </div>
            </div>
          </div>
        </FormItemRest>
      </template>
      <template #formfield2>
        <FormItemRest>
          <div
            class="flex mb-2 items-center"
            v-for="(item, index) in dataRef.insertTableFieldsList"
            :key="'formfield2' + index"
          >
            <div class="w-180px">{{ item.title }}</div>
            <div class="flex-1 flex items-center">
              <Input v-model:value="item.math" readonly />
              <a-button
                type="primary"
                class="ml-2"
                size="small"
                @click="handleSelectField2(item, index)"
                ghost
              >
                <SettingOutlined title="设置" />
              </a-button>
            </div>
          </div>
        </FormItemRest>
      </template>
    </BasicForm>
    <ConfigViewModal @register="registerModalConfigView" @success="handleSuccessConfigView" />
    <ConfigModulesModal
      @register="registerModalConfigModules"
      @success="handleSuccessConfigModules"
    />
  </ScrollContainer>
</template>

<script lang="ts" setup>
  import { ref, onMounted, computed, unref, reactive } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { ScrollContainer } from '/@/components/Container';
  import { Select, Input, Form, Divider } from 'ant-design-vue';
  import { PlusOutlined, MinusOutlined, SettingOutlined } from '@ant-design/icons-vue';
  import {
    formSchema,
    NodeList,
    FormDataOptions,
    getFormParams,
    setFormParams,
  } from './writeback.data';
  import {
    getIdeGetDbSources,
    getIdeGetTables,
    getAdminFlowGetTableColumns,
  } from '/@/api/flowManage/flowManage';
  import {
    getFormGetWriteBackPage,
    getFormUpdateWriteBack,
    getFormClearWriteBack,
    getFormClearWriteBackByDb,
    getFormGetWriteBackPageByDb,
    getFormUpdateWriteBackByDb,
  } from '/@/api/formDesign/formDesign';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { getFormList, getFormFields } from '/@/api/process/process';
  import { isArray } from '/@/utils/is';
  import { useModal } from '/@/components/Modal';
  import ConfigViewModal from './modules/configView/ConfigViewModal.vue';
  import ConfigModulesModal from './modules/configModules/ConfigModulesModal.vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  const { t } = useI18n();
  const loading = ref(false);
  const FormItemRest = Form.ItemRest;
  const InputTextArea = Input.TextArea;

  const emits = defineEmits(['success']);
  const props = defineProps({
    formCode: {
      type: String,
      default: '',
    },
  });

  const { createMessage } = useMessage();

  let dataRef: any = ref({
    //设置字段值
    writeBackFieldList: [
      {
        fieldName: '',
        writeBackMath: '',
        readonly: true,
      },
    ],
    //插入模块字段数组
    insertTableFieldsList: [] as FormDataOptions[],
  });

  const writeBackFieldListLen = computed(() => unref(dataRef).writeBackFieldList.length);

  const [registerForm, { setFieldsValue, getFieldsValue, updateSchema, resetFields, validate }] =
    useForm({
      labelWidth: 120,
      schemas: formSchema,
      showActionButtonGroup: false,
      actionColOptions: {
        span: 23,
      },
      // submitFunc: customSubmitFunc,
    });
  const initForm = async () => {
    initFormFn();
  };

  const initFormFn = async () => {
    await getFormData();
    // await getFlowNode();
    await getIdeGetDbSourcesDada();
    if (unref(type.value == 1)) {
      getFormGetWriteBackPageData();
    } else {
      getFormGetWriteBackPageByDbData();
    }
  };

  const writePropData = ref('');
  //获取表单回写
  const getFormGetWriteBackPageData = async () => {
    const params = {
      formCode: props.formCode,
    };
    const { writeProp } = await getFormGetWriteBackPage(params);
    writePropData.value = writeProp;
    const data = getFormParams({ writeProp });
    dataRef.value = {
      ...data,
    };
    console.log('dataRef', unref(dataRef));
    setFieldsValue({ ...unref(dataRef) });
    if (unref(dataRef).relateCode) {
      handleChangeForm(unref(dataRef).relateCode);
    }
    if (
      !isArray(unref(dataRef).writeBackFieldList) ||
      (isArray(unref(dataRef).writeBackFieldList) && unref(dataRef).writeBackFieldList.length == 0)
    ) {
      handleAdd();
    }
  };

  //获取数据源回写
  const getFormGetWriteBackPageByDbData = async () => {
    const params = {
      formCode: props.formCode,
    };
    const { writeProp } = await getFormGetWriteBackPageByDb(params);
    writePropData.value = writeProp;
    const data = getFormParams({
      writeProp,
    });
    dataRef.value = {
      ...data,
    };
    console.log('dataRef', unref(dataRef));
    setFieldsValue({ ...unref(dataRef) });
    if (unref(dataRef).dbSource) {
      // handleChangedbData(unref(dataRef).dbSource);
      getTablesData(unref(dataRef).dbSource);
    }
    if (unref(dataRef).relateCode) {
      handleChangeDataSource(unref(dataRef).relateCode);
    }
    if (
      !isArray(unref(dataRef).writeBackFieldList) ||
      (isArray(unref(dataRef).writeBackFieldList) && unref(dataRef).writeBackFieldList.length == 0)
    ) {
      handleAdd();
    }
  };

  const customSubmitFunc = async () => {
    try {
      const values = await validate();
      const formata = Object.assign({}, unref(dataRef), values);
      const data = setFormParams({
        writeProp: unref(writePropData),
        dataRef: formata,
        type: unref(type),
      });
      const params = {
        formCode: props.formCode,
        writeProp: data,
      };
      loading.value = true;
      if (unref(type) == 1) {
        await getFormUpdateWriteBack(params);
      } else {
        await getFormUpdateWriteBackByDb(params);
      }
      createMessage.success('保存成功');
      emits('success');
      // initForm();
      // emit('success', { isUpdate: unref(isUpdate), values: { ...values, id: rowId.value } });
    } finally {
      loading.value = false;
    }
  };
  //重置
  const handleResetFields = async () => {
    let params: Recordable = {
      formCode: props.formCode,
    };
    if (unref(type) == 1) {
      const record = getFieldsValue();
      params.opportunity = record.timestamp;
      await getFormClearWriteBack(params);
    } else {
      await getFormClearWriteBackByDb(params);
    }
    createMessage.success('清除成功');
    initForm();
  };
  onMounted(() => {
    initForm();
  });

  //新增字段值
  const handleAdd = () => {
    const params = {
      fieldName: '',
      writeBackMath: '',
      readonly: true,
    };
    if (isArray(dataRef.value.writeBackFieldList)) {
      dataRef.value.writeBackFieldList.push(params);
    } else {
      dataRef.value.writeBackFieldList = [];
      dataRef.value.writeBackFieldList.push(params);
    }
  };
  //删除字段值
  const handleDelete = (index) => {
    dataRef.value.writeBackFieldList.splice(index, 1);
  };

  //点击文本框
  const handleClickArea = (record, index) => {
    if (unref(type) == 1) {
      handleSelectField1(record, index);
    } else {
      const obj: any = tableFieldsData.value.find((item) => item.value == record.fieldName);
      if (obj && obj.type == 'string') {
        record.readonly = false;
      } else {
        handleSelectField1(record, index);
      }
    }
  };

  const currentCode = ref('');
  const formDataOptions = ref([]);
  const getFormData = () => {
    formDataOptions.value = [];
    getFormList().then((res) => {
      formDataOptions.value = res || [];
      if (isArray(formDataOptions.value) && formDataOptions.value.length) {
        formDataOptions.value.forEach((item: FormDataOptions) => {
          item.label = item.name;
          item.value = item.code;
        });
        updateSchema({
          field: 'relateCode',
          componentProps: {
            options: formDataOptions.value,
            onChange: handleChangeForm,
          },
        });
      }
    });
  };
  //表单change
  const handleChangeForm = (val) => {
    currentCode.value = val;
    getFieldsData();
  };
  const fieldsDataOptions = ref<FormDataOptions[]>([]);
  //获取表单对应字段
  const getFieldsData = async () => {
    try {
      const params = {
        formCode: unref(currentCode),
      };
      fieldsDataOptions.value = [];
      dataRef.value.insertTableFieldsList = [];
      fieldsDataOptions.value = (await getFormFields(params)) || [];
      fieldsDataOptions.value.forEach((item: any) => {
        delete item.options;
        item.label = item.title;
        item.value = item.name;
        dataRef.value.insertTableFieldsList.push({
          name: item.name,
          title: item.title,
          math: unref(dataRef)['insertFields']?.[item.name],
          kind: 'insert',
        });
      });

      updateSchema({
        field: 'primaryKey',
        componentProps: {
          options: unref(fieldsDataOptions),
        },
      });
    } catch (err) {
      console.log(err);
      loading.value = false;
    }
  };

  const [registerModalConfigView, { openModal: openConfigView }] = useModal();

  //配置条件
  const handleConfigView = () => {
    const record = getFieldsValue();
    if (!record['relateCode']) {
      return createMessage.warning(`请选择回写${unref(type) == 1 ? '表单' : '表格'}`);
    }
    openConfigView(true, {
      fields: unref(type) == 1 ? [...unref(fieldsDataOptions)] : [...unref(tableFieldsData)],
      list: unref(dataRef).conditionList,
      formCode: props.formCode,
      type: unref(type),
    });
  };
  //配置条件回调
  const handleSuccessConfigView = ({ list }) => {
    dataRef.value.conditionList = [];
    if (list.length) {
      dataRef.value.conditionList = [...list];
    }
  };

  //字段表达式
  const [registerModalConfigModules, { openModal: openConfigModules }] = useModal();

  const handleConfigModules = (kind) => {
    openConfigModules(true, {
      fields:
        unref(type) == 1
          ? unref(fieldsDataOptions)
          : unref(tableFieldsData)?.filter((item) => item.type == 'number'),
      formCode: props.formCode,
      kind,
      mathValue: unref(currentFormfieldMath),
      type: unref(type),
    });
  };
  //字段表达式回调
  const handleSuccessConfigModules = ({ mathValue, kind }) => {
    if (kind == 1) {
      dataRef.value.writeBackFieldList[unref(currentFormfieldIndex)].writeBackMath = mathValue;
    } else {
      dataRef.value.insertTableFieldsList[unref(currentFormfieldIndex)].math = mathValue;
    }
  };

  const currentFormfieldIndex = ref(-1);
  const currentFormfieldMath = ref('');
  //设置字段值表达式
  const handleSelectField1 = (record, index) => {
    currentFormfieldIndex.value = index;
    currentFormfieldMath.value = record.writeBackMath;
    if (!record?.fieldName) {
      return createMessage.warning('请选择字段值');
    }
    handleConfigModules(1);
  };
  //设置插入字段值表达式
  const handleSelectField2 = (record, index) => {
    currentFormfieldIndex.value = index;
    currentFormfieldMath.value = record.math;
    handleConfigModules(0);
  };

  //模块或者数据源
  const type = ref(1); //1是模块 2是数据源
  const handleType = async (val) => {
    type.value = val;
    resetFields();
    if (val == 2) {
      updateSchema([
        {
          field: 'dbSource',
          ifShow: true,
        },
        {
          field: 'relateCode',
          label: '回写表格',
          componentProps: {
            options: unref(tableDataSource),
            onChange: handleChangeDataSource,
          },
        },
        {
          field: 'divider-basic3',
          ifShow: false,
        },
        {
          field: 'primaryKey',
          ifShow: false,
        },
        {
          field: 'formfield2',
          ifShow: false,
        },
        {
          field: 'writeBackType',
          ifShow: false,
        },
      ]);
    } else {
      updateSchema([
        {
          field: 'dbSource',
          ifShow: false,
        },
        {
          field: 'relateCode',
          label: '回写表单',
          componentProps: {
            options: formDataOptions.value,
            onChange: handleChangeForm,
          },
        },
        {
          field: 'divider-basic3',
          ifShow: true,
        },
        {
          field: 'primaryKey',
          ifShow: true,
        },
        {
          field: 'formfield2',
          ifShow: true,
        },
        {
          field: 'writeBackType',
          ifShow: true,
        },
      ]);
    }
    initForm();
  };

  //获取数据源
  const dbDataSource = ref<any>([]);
  function getIdeGetDbSourcesDada() {
    dbDataSource.value = [];
    loading.value = true;
    getIdeGetDbSources()
      .then((res) => {
        const data = res || [];
        if (isArray(data) && data.length) {
          data.forEach((item: any) => {
            dbDataSource.value.push({
              ...item,
              label: item.name,
              value: item.name,
            });
          });
          updateSchema([
            {
              field: 'dbSource',
              componentProps: {
                options: unref(dbDataSource),
                onChange: handleChangedbData,
              },
            },
          ]);
        }
      })
      .finally(() => {
        loading.value = false;
      });
  }

  //数据源change
  const handleChangedbData = (val) => {
    dataRef.value.dbSource = val;
    setFieldsValue({ relateCode: '' });
    getTablesData(val);
  };

  //获取表名
  const tableDataSource = ref<any>([]);
  const getTablesData = async (val) => {
    try {
      tableDataSource.value = [];
      updateSchema([
        {
          field: 'relateCode',
          componentProps: {
            options: [],
          },
        },
      ]);
      if (!val) return;
      loading.value = true;
      const res = await getIdeGetTables({ dbSource: val });
      loading.value = false;
      if (isArray(res)) {
        res.forEach((item) => {
          tableDataSource.value.push({
            label: item,
            value: item,
          });
        });
        updateSchema([
          {
            field: 'relateCode',
            componentProps: {
              options: unref(tableDataSource),
            },
          },
        ]);
      }
    } catch (err) {
      console.log('getTablesData', err);
      loading.value = false;
    }
  };

  const handleChangeDataSource = (val) => {
    getFieldsDataSourceData(val);
  };

  const tableFieldsData = ref<any>();
  //获取表对应字段
  const getFieldsDataSourceData = async (val) => {
    try {
      const params = {
        dbSource: unref(dataRef).dbSource,
        tableName: val,
      };
      loading.value = true;
      tableFieldsData.value = [];
      const res = (await getAdminFlowGetTableColumns(params)) || [];
      loading.value = false;
      if (isArray(res)) {
        res.forEach((item) => {
          tableFieldsData.value.push({
            ...item,
            label: item.name,
            value: item.name,
          });
        });
      }
    } catch (err) {
      console.log(err);
      loading.value = false;
    }
  };
</script>
